package com.wxmp.wxcms.utils;

import com.google.common.collect.Maps;
import com.wxmp.core.util.PropertiesUtil;
import com.wxmp.wxcms.constants.ReaderPropertiesConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Map;
import java.util.Random;

/**
 * @author kaigejava
 */
@Controller
@Slf4j
public class UploadFileUtils {


    /**
     * @author kaigejava
     * @param file
     * @return
     */
    public  Map<String,Object> getFile(MultipartFile file) {
        Map<String,Object> map = Maps.newHashMap();
        try {
            //原文件名称
            String trueName = file.getOriginalFilename();
            //文件后缀名
            String ext = FilenameUtils.getExtension(trueName);

            //系统生成的文件名
            String fileName = System.currentTimeMillis() + new Random().nextInt(10000) + "." + ext;
            //图片上传路径
            String resUrl =  "";
            String filePath = "";
            String src = "";
            String upload = ReaderPropertiesConstant.UPLOAD;
            //读取配置文上传件的路径
           if(ReaderPropertiesConstant.EVN.equals(ReaderPropertiesConstant.LOCAL_EVN)){ //本地环境
               resUrl = ReaderPropertiesConstant.LOCAL_RES_UPLOAD_URL;
               filePath = ReaderPropertiesConstant.LOCAL_RES_UPLOAD_PATH+fileName;
               src = resUrl + upload+fileName;
           }else{   //线上环境
               resUrl = ReaderPropertiesConstant.ONLINE_RES_UPLOAD_URL;
               filePath = ReaderPropertiesConstant.ONLINE_RES_UPLOAD_PATH+ fileName;
               src = resUrl +fileName;
           }
            File saveFile = new File(filePath);
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }
            file.transferTo(saveFile);

            map.put("resUrl",resUrl);
            map.put("fileName",fileName);
            map.put("filePath",filePath);
            map.put("code",1);
            map.put("src",src);
        }catch (Exception e){
            log.info("===e:{}",e.getStackTrace());
        }
        return map;
    }

    /**
     * 添加图文的时候获取图片路径
     * @return
     */
    public String addNewsGetFilePath(){
        String filePath = "";
        String EVN = ReaderPropertiesConstant.EVN;
        if(EVN.equals(ReaderPropertiesConstant.LOCAL_EVN)){ //本地的
            filePath = ReaderPropertiesConstant.LOCAL_BASE_PATH;
        }else{
            filePath = ReaderPropertiesConstant.ONLINE_BASE_PATH;
        }
        return  filePath;
    }
}
